package com.tgy.clickhouse.datasource;

import com.tgy.clickhouse.config.RoutingDataSource;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Data
public class AIopsDynamicDatasource {
    public static final String MYSQL_DATASOURCE = "mysqlDataSource1";
    public static final String MYSQL_DATASOURCE_2 = "mysqlDataSource2";
    public static final String CLICKHOUSE_DATASOURCE = "clickHouseDataSource";

    @Bean
    @Primary
    @Qualifier("primaryDataSource")
    DataSource primaryDataSource(@Autowired @Qualifier(MYSQL_DATASOURCE) DataSource masterDataSource,
                                 @Autowired @Qualifier(MYSQL_DATASOURCE_2) DataSource slaveDataSource2,
                                 @Autowired @Qualifier(CLICKHOUSE_DATASOURCE) DataSource slaveDataSource) {

        System.out.println("create routing datasource...");
        Map<Object, Object> map = new HashMap<>();
        map.put(MYSQL_DATASOURCE, masterDataSource);
        map.put(MYSQL_DATASOURCE_2, slaveDataSource2);
        map.put(CLICKHOUSE_DATASOURCE, slaveDataSource);
        RoutingDataSource routing = new RoutingDataSource();
        routing.setTargetDataSources(map);
        routing.setDefaultTargetDataSource(masterDataSource);
        return routing;
    }
}
